﻿using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace TrinityAPI.Formatter
{
    public class PlainTextMediaTypeFormatter : MediaTypeFormatter
    {
        public PlainTextMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/plain"));
        }

        public override bool CanReadType(Type type)
        {
            return type == typeof(string) || type == typeof(JToken) || type == typeof(JValue);
        }

        public override bool CanWriteType(Type type)
        {
            return type == typeof(string) || type == typeof(JToken) || type == typeof(JValue);
        }

        public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream,
            HttpContent content, IFormatterLogger formatterLogger)
        {
            using (var sr = new StreamReader(readStream))
            {
                var request = await sr.ReadToEndAsync();
                if (request == null)
                    return null;
                return new JValue(request);
            }
        }
    }
}